package com.yjps.system.service;


import com.yjps.common.page.Pager;
import com.yjps.system.dao.PermissionDao;
import com.yjps.system.model.Permission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jessy on 2015/7/16.
 */
@Service("permissionService")
public class PermissionService{
    private Logger log = LoggerFactory.getLogger(PermissionService.class);
    @Resource
    private PermissionDao permissionDao;


    public Permission findPermission(int id) {
        return permissionDao.load(id);
    }

    public List<Permission> permissionList() {
        String hql = "from Permission p where p.isValid = 1";
        return permissionDao.find(hql);
    }

    public Pager<Permission> getPermissionByPager(Pager<Permission> pager) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String queryString = "from Permission t where t.isValid = 1";
        queryString += " order by t.id desc";
        List<Permission> accounts = permissionDao.findWithSelect(queryString, params, (pager.getPageNo()-1)*pager.getPageSize(), pager.getPageSize());
        pager.setCount(permissionDao.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

    @Transactional
    public void addPermission(Permission permission) {
        permissionDao.save(permission);
    }

    @Transactional
    public Permission updatePermission(Permission permission) {
        String hql = "update Permission p set p.permissionName =:permissionName,p.per_description =:per_description where p.id =:id";
        Map<String, Object> map = new HashMap<>();
        map.put("permissionName",permission.getPermissionName());
        map.put("per_description",permission.getPer_description());
        map.put("id",permission.getId());
        permissionDao.excute(hql, map);
        return permissionDao.load(permission.getId());
    }

    @Transactional
    public void deletePermisson(int id) {
        permissionDao.deleteById(id);
    }
    public Permission findPermissionByName(String permissionName) {
        String hql = "from Permission p where p.permissionName = :permissionName";
        Map<String, Object> map = new HashMap<>();
        map.put("permissionName", permissionName);
        return (Permission)permissionDao.findUniqueResult(hql, map);
    }
}
